/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 26, 2012  3:35:11 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.ps.outbound
 * File Name : SyncPrItemService.java
 * TODO
 */
package sap.business.mm.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.MmPurchaseRequest;
import jpa.entitys.synchro.staging.SyncAttachFile;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmPurchaseRequestServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import apps.common.SyncAttachFileAction;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class SyncPrItemService extends SynchroOutAbstract{
	
	private static final Logger log = Logger.getLogger(SyncPrItemService.class);
	private static MmPurchaseRequestServices mmPurchaseRequestServices = null;


	/**
	 * Date =Nov 12, 2013 : 2:32:40 PM 
	 * CreateBy=Chatree Siangklom
	 * SyncPrItemService
	 * TODO
	 */
	public SyncPrItemService() {
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, JCoTable jcoTableAttachFile, List<?> value_list,List<SyncAttachFile> attach_lst) throws Exception {		
		//Check Is not isEmpty is exit method.
		if(!jcoTable.isEmpty() || !jcoTableAttachFile.isEmpty())
		{
			System.out.println("Bapi="+ sap_bapi +", table="+ sap_table +" is not Empty ");
			return;
		}	
		
		if(CommonService.getSize(value_list) > 0){			
			System.out.println("value_list.size : " + CommonService.getSize(value_list) + ", attach_lst.size : " + CommonService.getSize(attach_lst));
			System.out.println("Befor Table NumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {
				MmPurchaseRequest model = (MmPurchaseRequest)obj;
				System.out.println("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " //DocumentNo = " + model.getDocumentNo());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				
				jcoTable.setValue("BUKRS", model.getSapCompanyCode());
				jcoTable.setValue("EKORG", model.getEbanEkorg());
				jcoTable.setValue("EKGRP", model.getEbanEkgrp());
				jcoTable.setValue("WERKS", model.getSapPlantCode());
				jcoTable.setValue("BSART", model.getTypeOfPurchase());
				jcoTable.setValue("PR_PROMIS", model.getDocumentNo());
				jcoTable.setValue("AFNAM", model.getRequestPerson());
				jcoTable.setValue("REQUEST_TEL", model.getRequestPersonTel());
				jcoTable.setValue("BNFPO", model.getLineSeqNo());
				jcoTable.setValue("KNTTP", model.getPorType());
				jcoTable.setValue("DEPART", model.getDepartmentCode());
				jcoTable.setValue("MATNR", model.getItemCode());
				jcoTable.setValue("TXZ01", model.getItemDesc());
				jcoTable.setValue("MENGE", model.getItemQty());
				jcoTable.setValue("MEINS", model.getItemUm());
				jcoTable.setValue("PREIS", model.getEbanPreis());
				jcoTable.setValue("WAERS", model.getCurrency());
				jcoTable.setValue("LGORT", model.getEbanLgort());
				jcoTable.setValue("BADAT", model.getPorDate());
				jcoTable.setValue("LFDAT", model.getRequiredByDate());
				jcoTable.setValue("FRGDT", model.getEbanFrgdt());
				jcoTable.setValue("EMLIF", model.getEbanEmlif());
				jcoTable.setValue("ANLN1", model.getEbknAnln1());
				jcoTable.setValue("SAKTO", model.getEbknSakto());
				jcoTable.setValue("KOSTL", model.getEbknKostl());
				
				//DR.TREE 
				//CHANGE TO SUPPORT PR SERVICE 
				//2013-04-04
				if(CommonService.IsNullRString(model.getPmsTypeOfPurchase()).equals("S")){
					if(CommonService.IsNullRString(model.getPropertyCategoty()).equals("L")){
						
						if(!CommonService.IsNull(model.getUnitNumber())) //Low Rise
						{
							jcoTable.setValue("ITMPLAN", model.getUnitNumber());
							jcoTable.setValue("TYPE", model.getUnitType());
						}
						else
							jcoTable.setValue("ITMPLAN", model.getBuildingCode()); //High Rise
						
					}else if(CommonService.IsNullRString(model.getPropertyCategoty()).equals("H")){
						jcoTable.setValue("ITMPLAN", model.getBuildingCode()); //High Rise
					}
				}else
				{
					if(!CommonService.IsNull(model.getUnitNumber())) //Low Rise
					{
						jcoTable.setValue("ITMPLAN", model.getUnitNumber());
						jcoTable.setValue("TYPE", model.getUnitType());
					}
					else
						jcoTable.setValue("ITMPLAN", model.getBuildingCode()); //High Rise
				}
				
				jcoTable.setValue("ITMTXT", model.getRemarks());
				jcoTable.setValue("PS_PSP_PNR", model.getEbknPsPspPnr());
				jcoTable.setValue("ABLAD", model.getModelName());
				jcoTable.setValue("CODE", model.getModelCode());
				
				//jcoTable.setValue("PS_PSP_PNR", model.getModelCode());
				
				if(model.getModelRevision() != null)
					jcoTable.setValue("WEMPF", model.getModelRevision() + "/" + model.getModelSubRevision());
				
				jcoTable.setValue("CREATE_DATE", model.getCreatedOn());
				jcoTable.setValue("APPROVE_DATE", model.getActionDate());
				jcoTable.setValue("APPROVE_BY", model.getActionBy());
				jcoTable.setValue("ITM_NOTE", model.getObjective());
				jcoTable.setValue("WEBAZ", model.getWebaz());
				jcoTable.setValue("PLIFZ", model.getPlifz());
				jcoTable.setValue("PURCH_TYP", model.getPurchTyp());
				jcoTable.setValue("USER_ID", model.getCreatedBy());
				jcoTable.setValue("CANCEL", model.getPrStatus());
				
				//For High rise for Contact COntrctor
				jcoTable.setValue("ACT_CODE", model.getActivityGroupCode());				
	        }
			
			if(CommonService.getSize(attach_lst) > 0){
				jcoTableAttachFile.deleteAllRows();
				for (SyncAttachFile value : attach_lst) {					
					jcoTableAttachFile.appendRow();
					jcoTableAttachFile.setValue("PR_PROMIS", value.getDocumentNo());
					jcoTableAttachFile.setValue("PICTURE_PATH", value.getFilePath());
				}
				
			}else 
				System.err.println("PR No Attach File !!!");
		}
				
		super.SynchroToSap(jcoFunction, jcoTable, jcoTableAttachFile, value_list, attach_lst);		
		System.out.println("After Table NumRows : " + jcoTable.getNumRows());
	}
	
	public void CallbackMessageFromSap(JCoTable jcoTable_return, List<SyncAttachFile> attach_lst) throws Exception {
		
		String msg = "S";
		String msg_desc = "Success";
		List<MmPurchaseRequest> lst = new ArrayList<MmPurchaseRequest>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			System.out.println("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				MmPurchaseRequest model = mmPurchaseRequestServices.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				System.out.println(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					if(CommonService.IsNull(model.getMsgCode())){
						msg = "E";
						msg_desc = "sap don't send message";
					}else if(!CommonService.IsNullRString(model.getMsgCode()).equals("S")){
						msg = model.getMsgCode();
						msg_desc = model.getMsgDesc();
					}
					
					lst.add(model);
				}
			}
			
			mmPurchaseRequestServices.Updated(lst);
			
			if(CommonService.getSize(attach_lst) > 0){
				List<SyncAttachFile> new_attach_lst = new ArrayList<SyncAttachFile>();
				for(SyncAttachFile model : attach_lst){
					model.setMsgCode(msg);
					model.setMsgDesc(msg_desc);
					model.setMsgAltDesc(null);
					model.setMsgActResult(null);
					model.setIssync("Y");
					model.setIsactive("Y");
					new_attach_lst.add(model);
				}
				new SyncAttachFileAction().Updated(new_attach_lst);		
			}
		}else
			System.out.println(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<MmPurchaseRequest> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<MmPurchaseRequest> newlst = new ArrayList<MmPurchaseRequest>();
				for(MmPurchaseRequest model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new MmPurchaseRequestServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){

			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
		}finally{
			System.out.println("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	/**
	 * 
	 * @param value_list
	 * @throws Exception
	 */
	public void SendingToSAP(List<MmPurchaseRequest> value_list) throws Exception  {
		if(!CommonService.IsNull(value_list)){
			try
			{
				this.sap_bapi = "ZIN_MMPUR_PR";
				this.sap_table = "T_DATA";
				String sap_table_attach = "T_ATTACH";
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();

				List<SyncAttachFile> attach_lst = ((MmPurchaseRequest)value_list.get(0)).getAttachFile();

				//Get SAP BAPI function 
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				
				//GetTable Attach File
				JCoTable jcoTableAttachFile = jco_conn.getTables(sap_table_attach);
				
				mmPurchaseRequestServices = new MmPurchaseRequestServices(this.emSynchro);
				SynchroToSap(jcoFunction, jcoTable, jcoTableAttachFile, value_list, attach_lst);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return, attach_lst);
			
			}catch(Exception e)
			{
				UpdateStagingWhenError(value_list, e);
				
				log.error(e.getMessage());
				System.err.println(e.getMessage());
				
				throw e;
			}
		}
	}
	
	@Deprecated
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_MMPUR_PR";
		this.sap_table = "T_DATA";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();

		//Get SAP BAPI function 
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		mmPurchaseRequestServices = new MmPurchaseRequestServices(this.emSynchro);
		List<MmPurchaseRequest> value_list = mmPurchaseRequestServices.findAllIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}
	
//	public static void main(String [] args)
//	{		
//		try {
//			SyncPrItemService xx = new SyncPrItemService();
//			xx.Start();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}

}
